import { isObject, deepMerge } from './utils';
import { AxiosResponseHeaders, RequestMethod } from '../types';

function normalizeHeaderName(headers: any, normalizedName: string): void {
  if (!headers) {
    return;
  }
  Object.keys(headers).forEach(key => {
    if (key !== normalizedName && key.toUpperCase() === normalizedName.toUpperCase()) {
      headers[normalizedName] = headers[key];
      delete headers[key];
    }
  });
}

export function processHeaders(headers: any, data: any): any {
  normalizeHeaderName(headers, 'Content-Type');
  if (isObject(data)) {
    if (headers && !headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8';
    }
  } else {
    delete headers['Content-Type'];
  }
  return headers;
}

export function parseHeaders(headers: string): any {
  return headers.split('\n').reduce((acc: AxiosResponseHeaders, cur) => {
    let [key, ...value] = cur.split(':');
    if (!key) return acc;
    acc[key.toLocaleLowerCase()] = value.join(':').trim();
    return acc;
  }, Object.create(null));
}

export function flattenHeaders(headers: any, method: RequestMethod): any {
  if (!headers) {
    return headers;
  }
  headers = deepMerge(headers['common'], headers[method], headers);
  const headersToDelete = ['get', 'delete', 'common', 'head', 'post', 'put', 'patch', 'options'];
  headersToDelete.forEach(method => {
    delete headers[method];
  });
  return headers;
}
